const { Url } = require("url")
const format = require("url").format

const db = require('../../model/index')
const utilx = require('../../lib/utilx')
const responser = require('../../lib/responser');
const {Check, CheckNull} = require("../../lib/check");

const config = require("../../config/config")
const staticPrefix = config.staticPrefix

const Model = db.models
const Carousel = Model.Carousel


module.exports = (router) => {
    router.get("/carousels/all", async (ctx) => {
        var URL = new Url()
        URL.protocol = staticPrefix.protocol
        URL.hostname = staticPrefix.hostname
        URL.port = staticPrefix.port

        var pictures = await Carousel.findAll({
            order : [["createdAt","DESC"]]
        }).map((carousel) => {
            URL.pathname = carousel.img
            carousel.img = format(URL)
            return carousel
        })

        responser.success(ctx,pictures)
    })

    router.post("/admin/carousels/add", async (ctx) => {
        Check(ctx,"href","img")

        var body = ctx.request.body
        var picture = await Carousel.create({
            img : body.img,
            href : body.href
        })

        responser.success(ctx,picture)
    })

    router.post("/admin/carousels/del", async (ctx) => {
        Check(ctx,"id")

        var body = ctx.request.body
        await Carousel.destroy({
            where : {
                id : body.id
            }
        })

        responser.success(ctx,{
            result : "ok"
        })
    })
}